package cn.icanci.ladybird.service.util.impl;

import cn.icanci.ladybird.service.util.SendSmsService;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author: icanci
 * @date: Created in 2020/10/3 21:24
 * @classAction: 阿里云短信发送的实现类
 */
@Service
public class SendSmsServiceImpl implements SendSmsService {
    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {
        /**
         * 连接阿里云
         */
        DefaultProfile profile =
                DefaultProfile.getProfile(
                        // 不需要改
                        "cn-hangzhou",
                        // key
                        "LTAI4G4JptDwzhS624rapUz2",
                        // pwd
                        "jKrNsVyG1jhYkWN5g6V5v3IzQZoGZS"
                );
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        // 构建请求
        request.setSysMethod(MethodType.POST);
        // 官方提供，不需要修改
        request.setSysDomain("dysmsapi.aliyuncs.com");
        // 官方提供，不需要修改 版本号
        request.setSysVersion("2017-05-25");
        // 不需要修改
        request.setSysAction("SendSms");
        // 自定义的参数 （手机号，验证码，签名，模板）
        // 自定义手机号
        request.putQueryParameter("PhoneNumbers", phoneNum);
        // 自定义签命
        request.putQueryParameter("SignName", "是小猪童鞋啦");
        // 自定义模板 Code
        request.putQueryParameter("TemplateCode", templateCode);
        // 自定义验证码
        request.putQueryParameter("TemplateParam", JSON.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            // 是否成功
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
